package com.atguigu.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.config.AlipayConfig;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.result.RetVal;
import com.atguigu.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET;
import static com.alipay.api.AlipayConstants.SIGN_TYPE;

/**
 * <p>
 * 支付信息表 前端控制器
 * </p>
 *
 * @author 
 * @since 2022-09-16
 */
@RestController
@RequestMapping("/payment")
public class PaymentInfoController {

    @Autowired
    private PaymentInfoService paymentInfoService;

    //1.创建支付二维码 //api.gmall.com/payment/createQrCode/{orderId}
    @RequestMapping("createQrCode/{orderId}")
    public String createQrCode(@PathVariable Long orderId)throws Exception{
        return paymentInfoService.createQrCode(orderId);
    }

    //2.支付成功后的异步通知
    @PostMapping("/async/notify")
    public String asyncNotify(@RequestParam Map<String,String> alipayParam) throws Exception {
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(alipayParam, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        if(signVerified){
            //验签成功之后的逻辑
            String tradeStatus = alipayParam.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)||"TRADE_FINISHED".equals(tradeStatus)){
                String outTradeNo = alipayParam.get("out_trade_no");
                PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(outTradeNo);
                String paymentStatus = paymentInfo.getPaymentStatus();
                if (paymentStatus.equals(PaymentStatus.PAID.name())||paymentStatus.equals(PaymentStatus.ClOSED.name())){
                    return "success";
                }
            }
            //修改支付订单
            paymentInfoService.updatePaymentInfo(alipayParam);
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
        return "failure";
    }


    //3.退款接口
    @GetMapping("refund/{orderId}")
    public boolean refund(@PathVariable Long orderId){
        return paymentInfoService.refund(orderId);
    }
    //4.查询支付宝是否有交易记录
    @GetMapping("queryAlipayTrade/{orderId}")
    public boolean queryAlipayTrade(@PathVariable Long orderId){
        return paymentInfoService.queryAlipayTrade(orderId);
    }
    //5.交易关闭
    @GetMapping("closeAlipayTrade/{orderId}")
    public boolean closeAlipayTrade(@PathVariable Long orderId){
        return paymentInfoService.closeAlipayTrade(orderId);
    }
}

